package com.piao.springboot_interceptor.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录拦截器：检查登录状态，没登录则不能进入首页
// 1.@Component
// 2.implements HandlerInterceptor
@Component
public class LoginInterceptor implements HandlerInterceptor {
    //在DispatcherServlet之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("1.我是在DispatcherServlet之前执行的方法");
        Object loginUser = request.getSession().getAttribute("loginUser");//获取已登录的用户名
        if (loginUser == null) {
            //未登录，返回登陆页面
            request.setAttribute("msg", "请先登录");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        } else {
            //已登录，放行请求
            return true;
        }
    }

    //在controller执行之后的DispatcherServlet之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("2.在controller执行之后的DispatcherServlet之后执行");
    }

    //在页面渲染完成返回给客户端之前执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("3.在页面渲染完成返回给客户端之前执行");
    }
}
